package gupao.concurrency.concurrent.utils;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
public class ConcurrentHashMapSample {
    public static void main(String[] args) {
       /* Map<String, String> map = new HashMap<>();
        String key = "key";
        if(map.get(key) == null ){
            if(map.containsKey(key)){
                //key -> null
            } else{
                //key 不存在
            }
        }*/

        Map<String, List<Integer>> map = getProductItemListMap();
        map.forEach((productCode, itemIdList) -> {
            log.info("[productCode = {}, itemIds = ( {} )]", productCode,
                    String.join(",", itemIdList.stream().map(String::valueOf).toArray(String[]::new)));
        });
    }


    /**
     * computeIfAbsent sample
     *
     * @return
     */
    static Map<String, List<Integer>> getProductItemListMap() {
        ConcurrentHashMap<String, List<Integer>> productItemListMap = new ConcurrentHashMap<>();
        List<Product> productList = generateProducts();
        for (Product p : productList) {
            List<Integer> itemList = productItemListMap.computeIfAbsent(p.getProductCode(), k -> new ArrayList<>());
            itemList.add(p.getItemId());
        }
        return productItemListMap;
    }

    static List<Product> generateProducts() {
        List<Product> rt = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            rt.addAll(newProducts());
        }
        return rt;
    }

    static List<Product> newProducts(){
        List<Product> rt = new ArrayList<>();
        Product p = new Product(mockProductCode(), mockItemId());
        rt.add(p);
        char[] codeCharArray = p.getProductCode().toCharArray();
        int x = 3;
        for(char c: codeCharArray){
            if(Character.isDigit(c)){
                x = c - '0';
            }
        }
        for( int i = 0; i < x; i++){
            rt.add(new Product(p.getProductCode(), mockItemId()));
        }
        return rt;
    }

    static String mockProductCode() {
        String u = UUID.randomUUID().toString();
        int x = u.lastIndexOf("-") + 1;
        return "P" + u.substring(x);
    }

    static int mockItemId() {
        Double x = Math.random() * 100000000;
        return x.intValue();
    }

    @Getter
    @Setter
    @AllArgsConstructor
    static class Product {
        String productCode;
        Integer itemId;
    }

}